//
//  AdsManager.m
//  KKSDK
//  Created by jay Win on 2019/3/8.
//  Copyright © 2019 jay Win. All rights reserved.
#import "AdsManager.h"
#import "MoPub.h"
#import "Analytics.h"
#import "AdsConfig.h"
#import "Adjust.h"

@interface AdsManager ()<MPInterstitialAdControllerDelegate,MPRewardedVideoDelegate,MPAdViewDelegate>
@property(nonatomic,copy)void(^onBannerImpression)(void);
@property(nonatomic,copy)void(^onBannerLoadFailed)(void);

@property(nonatomic,copy)void(^onVideoOpen)(void);
@property(nonatomic,copy)void(^onVideoClose)(void);
@property(nonatomic,copy)void(^onVideoComplete)(void);

@property NSString *idfa;
@property BOOL showAdsLog;
@property BOOL completeRewardVideo;
@property BOOL isRequestingInterstitial;
@property BOOL isRequestingRewardVideo;
@property BOOL isLoadedInterstitial;
@property BOOL isLoadedRewardVideo;


@property int adsIntervalTime;
@property double initAdsTime;
@property double lastCloseAdsTime;

@property double lastLoadInterstitialTime;
@property double lastLoadRewardVideoTime;

@property(nonatomic)MPAdView *bannerView;
@property(nonatomic,strong)MPInterstitialAdController *interstitial;

@end
@implementation AdsManager

+(instancetype)shareInstance{
    static AdsManager *manager=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AdsManager new];
    });
    return manager;
}
- (void)initMopub:(UIViewController *)rootViewController enableLog:(BOOL)debug{
    [Analytics setTkTrackEvent:@"INIT_ADS" params:nil];
    _initAdsTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    [AdsConfig refreshAdDate];
    _idfa=[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    if(AdsConfig.rewardVideo_ID==nil){
        NSLog(@"初始化广告id尚未配置，请确认已读取配置");
        return;
    }else{
        self.rewardID=AdsConfig.rewardVideo_ID;
    }
    self.bannerID=AdsConfig.banner_ID;
    self.padBannerID=AdsConfig.pad_banner_ID;
    self.interstittialID=AdsConfig.interstitial_ID;
    self.showAdsLog=debug;

    if(self.showAdsLog&&_idfa){
        NSLog(@"======IDFA:%@",_idfa);
    }
    self.rootViewController=rootViewController;
    MPMoPubConfiguration *config =[[MPMoPubConfiguration alloc]initWithAdUnitIdForAppInitialization:self.rewardID];
    if(self.showAdsLog){
        config.loggingLevel=MPBLogLevelInfo;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [[MoPub sharedInstance]initializeSdkWithConfiguration:config completion:^(){
             double initSuccedTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]-self.initAdsTime;
            NSLog(@"广告初始化成功，所需时长:%f",initSuccedTime);
            [Analytics logFacebookFirebaseThinkEvent:INIT_SUCCEED params:@{@"INIT_SUCCEED_TIME":@(initSuccedTime)}];
            [self.delegate onAdsListener:INIT_SUCCEED];
        }];
    });
}
-(void)parseImpressionDataToDict:(MPImpressionData *)impressionData{
    if (impressionData == nil)
    {
        return;
    }
    NSError *jsonSerializationError = nil;
    NSObject *impressionObject = [NSJSONSerialization JSONObjectWithData:impressionData.jsonRepresentation options:0 error:&jsonSerializationError];
    NSDictionary* dict = [impressionObject isKindOfClass:NSDictionary.class] ? (NSDictionary *)impressionObject : nil;
    if (dict == nil)
    {
        return ;
    }
    [self logAdsInfo:@"获取的时时广告数据回传如下:"];
    NSMutableDictionary *obj = [NSMutableDictionary dictionary];
    
    NSString *adFormat=[dict objectForKey:@"adunit_format"];
    [obj setObject:adFormat forKey:AD_FORMAT];
    if(_idfa){
         [obj setObject:_idfa forKey:AD_IDFA];
    }else{
          [obj setObject:@"" forKey:AD_IDFA];
    }
    if([Adjust attribution].network){
            [obj setObject:[Adjust attribution].network forKey:AD_USER_SOURCE];
    }else{
            [obj setObject:@"Unknow" forKey:AD_USER_SOURCE];
    }

    if([adFormat isEqualToString:@"Banner"]){
        [AdsConfig addBannerImpressionTime];
        [obj setObject:@([AdsConfig getBannerImpressionTimes]) forKey:AD_ALL_BA];
    }else if([adFormat isEqualToString:@"Fullscreen"]){
        [AdsConfig addInterstitialImpressionTime];
        [AdsConfig addInterstitialImpressionTimeInDay];
        [obj setObject:@([AdsConfig getInterstitialImpressionTimes]) forKey:AD_ALL_IN];
        [obj setObject:@([AdsConfig getInterstitialImpressionTimesInDay]) forKey:AD_DAY_IN];
    
    }else if([adFormat isEqualToString:@"Rewarded Video"]){
        [AdsConfig addRewardVideoImpressionTimesInDay];
        [AdsConfig addRewardVideoImpressionTimes];
        [obj setObject:@([AdsConfig getRewardVideoImpressionTimes]) forKey:AD_ALL_RE];
        [obj setObject:@([AdsConfig getRewardVideoImpressionTimesInDay]) forKey:AD_DAY_RE];
    }
    
 
    if([dict objectForKey:@"adunit_name"]){
         [obj setObject:[dict objectForKey:@"adunit_name"] forKey:AD_PLACEMENT_NAME];
    }
    if([dict objectForKey:@"network_name"]){
          [obj setObject:[dict objectForKey:@"network_name"] forKey:AD_NETWORK];
    }else{
        [obj setObject:@"unKonw_netWork" forKey:AD_NETWORK];
    }
    if([dict objectForKey:@"adgroup_name"]){
        [obj setObject:[dict objectForKey:@"adgroup_name"] forKey:AD_ITEM_NAME];
    }
    if([dict objectForKey:@"adgroup_type"]){
       [obj setObject:[dict objectForKey:@"adgroup_type"] forKey:AD_TYPE];
    }
    if([dict objectForKey:@"network_placement_id"]){
         [obj setObject:[dict objectForKey:@"network_placement_id"] forKey:AD_NETWORK_ID];
    }
    if([dict objectForKey:@"country"]){
        [obj setObject:[dict objectForKey:@"country"] forKey:AD_COUNTRY];
    }
    if([dict objectForKey:@"currency"] ){
        [obj setObject:[dict objectForKey:@"currency"] forKey:AD_CURRENCY];
    }
    if([dict objectForKey:@"precision"]){
        [obj setObject:[dict objectForKey:@"precision"] forKey:AD_PRECISION];
    }
    if([dict objectForKey:@"publisher_revenue"]){
          [obj setObject:[dict objectForKey:@"publisher_revenue"] forKey:AD_REVENUE];
    }

    [self logAdsInfo:obj.description];
    [Analytics setTkTrackEvent:@"AD_IM" params:dict];
}
-(void)logAdsInfo:(NSObject *)obj{
    if(self.showAdsLog)
    NSLog(@"===========%@",obj);
}
- (void)setAdsIntervals:(int)cdTime{
    NSLog(@"此功能已经弃用");
//    self.adsIntervalTime=cdTime;
}
-(BOOL)isCanPlayAds{
    double deltaTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]-self.lastCloseAdsTime;
    if (deltaTime>self.adsIntervalTime) {
        return  YES;
    }else{
        if(self.showAdsLog)
        NSLog(@"=========还剩%f秒",self.adsIntervalTime-deltaTime);
        return  NO;
    }
}

#pragma mark   banenr

- (void)requestBanner:(UIView *)container{
    NSString *selectedBannerID=iPad?self.padBannerID:self.bannerID;
    CGSize size=iPad?MOPUB_LEADERBOARD_SIZE:MOPUB_BANNER_SIZE;
    self.bannerView= [[MPAdView alloc] initWithAdUnitId:selectedBannerID size:size];
    self.bannerView.delegate=self;
    [self.bannerView loadAd];
    [Analytics logFacebookFirebaseThinkEvent:BANNER_REQUEST params:nil];
}
- (void)showBanner:(UIView *)container onImpressionEvent:(void (^)(void))onImpression onFailed:(void (^)(void))onFailed{
    [self logAdsInfo:@"iOS请求banner"];
    _bannerContainer=container;
    _onBannerImpression=onImpression;
    _onBannerLoadFailed=onFailed;
    [self requestBanner:container];
}

- (void)showBanner:(UIView *)container position:(BOOL)isTop{
     [self logAdsInfo:@"Unity请求banner"];
    _bannerContainer=container;
     self.runInUnity=YES;
     self.bannerInTop=isTop;
    [Analytics logFacebookFirebaseThinkEvent:BANNER_REQUEST params:nil];
    [self requestBanner:self.bannerContainer];
}
- (void)hideBanner{
    [self logAdsInfo:@"隐藏banner"];
    self.runInUnity=NO;
    [self.bannerView removeFromSuperview];
    self.bannerView = nil;
}
#pragma mark   BannerDelegate

-(void)mopubAd:(id<MPMoPubAd>)ad didTrackImpressionWithImpressionData:(MPImpressionData *)impressionData{
    [self parseImpressionDataToDict:impressionData];
}
- (UIViewController *)viewControllerForPresentingModalView{
    return  self.rootViewController;
}
- (void)adViewDidLoadAd:(MPAdView *)view{
    if(self.runInUnity){
        [self logAdsInfo:@"Unity端banner加成功"];
        if(iPad){
            self.bannerView.frame = CGRectMake((SCREENWIDTH - view.adContentViewSize.width) / 2,
                                               self.bannerInTop?0:SCREENHEIGHT - view.adContentViewSize.height,
                                               view.adContentViewSize.width,view.adContentViewSize.height);
        }else if(IPhoneX){
            self.bannerView.frame = CGRectMake((SCREENWIDTH -view.adContentViewSize.width) / 2,
                                               self.bannerInTop?44:SCREENHEIGHT - view.adContentViewSize.height-34,
                                               view.adContentViewSize.width,view.adContentViewSize.height);
            
        }else if(IPHONE){
            self.bannerView.frame = CGRectMake((SCREENWIDTH- view.adContentViewSize.width) / 2,
                                               self.bannerInTop?0:SCREENHEIGHT- view.adContentViewSize.height,
                                               view.adContentViewSize.width,view.adContentViewSize.height);
        }
        [self.bannerContainer addSubview:self.bannerView];
        [self.delegate onAdsListener:BANNER_IM];
        
    }else{
        if(_onBannerImpression)
        _onBannerImpression();
        _onBannerImpression=nil;
        [[self bannerContainer]addSubview:view];
        [self.delegate onAdsListener:BANNER_IM];
    }
    [Analytics logAdjustEvent:AdsConfig.adjust_banner_impression];
    [Analytics logFacebookFirebaseThinkEvent:BANNER_IM params:nil];
}
- (void)adView:(MPAdView *)view didFailToLoadAdWithError:(NSError *)error{
    NSLog(@"Banner加载失败%@",error.localizedDescription);
    if(_onBannerLoadFailed)
    _onBannerLoadFailed();
    _onBannerLoadFailed=nil;
    [Analytics logFacebookFirebaseThinkEvent:BANNER_FAILED params:@{@"errorCode":error.localizedDescription}];
    [self.delegate onAdsListener:BANNER_FAILED];
}


#pragma mark   Interstitial
- (void)requestInterstitial{
    if(_isRequestingInterstitial)//插屏正在请求中
        return;
    
    [self logAdsInfo:@"请求插屏广告"];
    _isLoadedInterstitial=NO;
    self.isRequestingInterstitial=YES;
    
    [Analytics logFacebookFirebaseThinkEvent:INTERSTITIAL_REQUESTING params:nil];
    self.lastLoadInterstitialTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.interstitial=[MPInterstitialAdController interstitialAdControllerForAdUnitId:AdsConfig.interstitial_ID];
        self.interstitial.delegate=self;
        [self.interstitial loadAd];
    });
}


- (BOOL)hasInterstitial{
    if(_isLoadedInterstitial){
        return YES;
    }else{
        if(!_isRequestingInterstitial){//如果插屏没有正在加载中 上报弥补事件
           [Analytics setTkTrackEvent:INTERSTITIAL_REMEDY params:nil];
        }
        [self requestInterstitial];
        return NO;
    }
}
- (void)showInterstitial{
    _isLoadedInterstitial=NO;//重置加载成功标志符
    [Analytics logFacebookFirebaseThinkEvent:INTERSTITIAL_SHOW params:nil];
    [self.interstitial showFromViewController:self.rootViewController];
}
- (void)showInterstitial:(void (^)(void))onOpen onCloseEvent:(void (^)(void))onClose{
    _isLoadedInterstitial=NO;//重置加载成功标志符
    _completeRewardVideo=NO;
    _onVideoOpen=onOpen;
    _onVideoClose=onClose;
    [self showInterstitial];
}
#pragma mark   InterstitialDelegate
- (void)interstitialDidReceiveTapEvent:(MPInterstitialAdController *)interstitial{
    [self logAdsInfo:@"插屏广告被点击"];
    [Analytics logFacebookFirebaseThinkEvent:INTERSTITIAL_CLICK params:nil];
}
- (void)interstitialDidLoadAd:(MPInterstitialAdController *)interstitial{
    _isLoadedInterstitial=YES;
    self.isRequestingInterstitial=NO;
    double loadTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]-self.lastLoadInterstitialTime;
    [self logAdsInfo:@"插屏广告加载成功"];
    [self.delegate onAdsListener:INTERSTITIAL_LOADED];
    [Analytics logFacebookFirebaseThinkEvent:INTERSTITIAL_LOADED params:@{@"loadTime":@(loadTime)}];
}
-(void)interstitialDidFailToLoadAd:(MPInterstitialAdController *)interstitial withError:(NSError *)error{
    self.isRequestingInterstitial=NO;
    _isLoadedInterstitial=NO;
    [self logAdsInfo:@"插屏广告加载失败"];
    [self.delegate onAdsListener:INTERSTITIAL_FAILED];
    [Analytics logFacebookFirebaseThinkEvent:INTERSTITIAL_FAILED params:@{@"errorCode":error.localizedDescription}];
}
- (void)interstitialDidAppear:(MPInterstitialAdController *)interstitial{
    [self logAdsInfo:@"插屏广告打开"];

    if(_onVideoOpen)
    _onVideoOpen();
    [Analytics logFacebookFirebaseThinkEvent:INTERSTITIAL_OPEN params:nil];
    [self.delegate onAdsListener:INTERSTITIAL_OPEN];
}

- (void)interstitialDidDisappear:(MPInterstitialAdController *)interstitial{
    [self logAdsInfo:@"插屏广告关闭"];
    if(_onVideoClose)
    _onVideoClose();
    self.lastCloseAdsTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    [Analytics logFacebookFirebaseThinkEvent:INTERSTITIAL_IM params:nil];
    [Analytics logAdjustEvent:AdsConfig.adjust_interstitial_impression];
    [self.delegate onAdsListener:INTERSTITIAL_CLOSE];
    [self requestInterstitial];
}


#pragma mark   RewardVideo
- (void)requestRewardVideo{
    if(_isRequestingRewardVideo)//正在请求中
        return;
    _isLoadedRewardVideo=NO;//重置加载完成标识符
    _isRequestingRewardVideo=YES;
    [self logAdsInfo:@"请求激励视频"];
    self.lastLoadRewardVideoTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    [Analytics logFacebookFirebaseThinkEvent:REWARD_REQUESTING params:nil];
    dispatch_async(dispatch_get_main_queue(), ^{
        [MPRewardedVideo loadRewardedVideoAdWithAdUnitID:self.rewardID withMediationSettings:nil];
        [MPRewardedVideo setDelegate:self forAdUnitId:self.rewardID];
    });
}
- (BOOL)hasRewardVideo{
    if(_isLoadedRewardVideo){
        return YES;
    }else{
        if(!_isRequestingRewardVideo){//激励没有正在请求 上报弥补事件
            [Analytics setTkTrackEvent:REWARD_REMEDY params:nil];
        }
        [self requestRewardVideo];
        return NO;
    }
}
- (void)setRewardVideoAutoPlayWhenLoadedStatus:(BOOL)enable{
    self.autoPlayRewardVideo=enable;
}
- (void)showRewardVideo{
    _isLoadedRewardVideo=NO;
    [Analytics logFacebookFirebaseThinkEvent:REWARD_SHOW params:nil];
    [MPRewardedVideo presentRewardedVideoAdForAdUnitID:self.rewardID fromViewController:self.rootViewController withReward:nil];
}
- (void)showRewardVideo:(void (^)(void))onOpen onCloseEvent:(void (^)(void))onClose onCompleteEvent:(void (^)(void))onComplete{
    _isLoadedRewardVideo=NO;
    _onVideoOpen=onOpen;
    _onVideoClose=onClose;
    _onVideoComplete=onComplete;
    [self showRewardVideo];
}
#pragma mark   RewardVideoDelegate

- (void)didTrackImpressionWithAdUnitID:(NSString *)adUnitID impressionData:(MPImpressionData *)impressionData{
    [self logAdsInfo:@"激励广告展示数据回传"];
    [self parseImpressionDataToDict:impressionData];
}

- (void)rewardedVideoAdDidLoadForAdUnitID:(NSString *)adUnitID{
    self.isRequestingRewardVideo=NO;
    _isLoadedRewardVideo=YES;
    [self logAdsInfo:@"激励视频加载成功"];
    double loadTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]-self.lastLoadRewardVideoTime;
    [self.delegate onAdsListener:REWARD_LOADED];
    [Analytics logFacebookFirebaseThinkEvent:REWARD_LOADED params:@{@"loadTime":@(loadTime)}];
    if(self.autoPlayRewardVideo){
        [self showRewardVideo];
    }
}
- (void)rewardedVideoAdDidFailToPlayForAdUnitID:(NSString *)adUnitID error:(NSError *)error{
    [self logAdsInfo:@"激励视频播放失败"];
    [Analytics logFacebookFirebaseThinkEvent:REWARD_PLAY_ERROR params:@{@"errorCode":error.localizedDescription}];
}
- (void)rewardedVideoAdDidReceiveTapEventForAdUnitID:(NSString *)adUnitID{
    [self logAdsInfo:@"激励视频点击"];
    [Analytics logFacebookFirebaseThinkEvent:REWARD_CLICK params:nil];
}
- (void)rewardedVideoAdWillLeaveApplicationForAdUnitID:(NSString *)adUnitID{
    [self logAdsInfo:@"激励视频途退出aapp"];
    [Analytics logFacebookFirebaseThinkEvent:REWARD_LEFT params:nil];
}
- (void)rewardedVideoAdDidDisappearForAdUnitID:(NSString *)adUnitID{
    self.autoPlayRewardVideo=NO;
    self.lastCloseAdsTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    if(self.completeRewardVideo){
        [self logAdsInfo:@"完成观看激励视频"];
        [Analytics setTkTrackEvent:REWARD_COMPLETE params:nil];
        if(_onVideoComplete)
        _onVideoComplete();
    }else{
        [self logAdsInfo:@"中途关闭广告"];
         [Analytics setTkTrackEvent:REWARD_CLOSE params:nil];
        if(_onVideoClose)
        _onVideoClose();
    }
    [self.delegate onAdsListener:self.completeRewardVideo?REWARD_COMPLETE:REWARD_CLOSE];
    [self requestRewardVideo];
}
- (void)rewardedVideoAdDidFailToLoadForAdUnitID:(NSString *)adUnitID error:(NSError *)error{
    NSLog(@"=======激励广告加载失败原因%@",error.localizedDescription);
    self.isRequestingRewardVideo=NO;
    [self.delegate onAdsListener:REWARD_FAILED];
    [Analytics logFacebookFirebaseThinkEvent:REWARD_FAILED params:@{@"errorCode":error.localizedDescription}];
}
- (void)rewardedVideoAdDidAppearForAdUnitID:(NSString *)adUnitID{
    [self logAdsInfo:@"激励打开"];
    self.completeRewardVideo=NO;
    self.autoPlayRewardVideo=NO;
    if(_onVideoOpen)
    _onVideoOpen();
    [self.delegate onAdsListener:REWARD_OPEN];
    [Analytics logFacebookFirebaseThinkEvent:REWARD_OPEN params:nil];
}
- (void)rewardedVideoAdShouldRewardForAdUnitID:(NSString *)adUnitID reward:(MPRewardedVideoReward *)reward{
    self.completeRewardVideo=YES;
    [self logAdsInfo:@"奖励用户"];
    [Analytics logFacebookFirebaseThinkEvent:REWARD_IM params:nil];
    [Analytics logAdjustEvent:AdsConfig.adjust_reward_impression];
}
@end
